package 信号量Semaphore;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreDemo implements Runnable{
    Semaphore semaphore = new Semaphore(2);// 允许三个线程进入临界区

    @Override
    public void run() {
        try {
            semaphore.acquire();
            System.out.println(Thread.currentThread().getName() + " 进入临界区");
            Thread.sleep(1000);// 不让一个线程马上重复进入!
            semaphore.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(10);// 线程池有20个线程
        SemaphoreDemo semaphoreDemo = new SemaphoreDemo();
        for (int i = 0; i < 10; i++) {
            service.submit(semaphoreDemo);
        }
    }
    // 两组两组的每隔1s出现

        //pool-1-thread-1 进入临界区
        //pool-1-thread-2 进入临界区

        //pool-1-thread-3 进入临界区
        //pool-1-thread-4 进入临界区

        //pool-1-thread-5 进入临界区
        //pool-1-thread-6 进入临界区

        //pool-1-thread-7 进入临界区
        //pool-1-thread-8 进入临界区

        //pool-1-thread-9 进入临界区
        //pool-1-thread-10 进入临界区
}
